<#
.SYNOPSIS
    This scripts helps to install a SharePoint Cumulative Update.
	
.DESCRIPTION
    This script helps to install the SharePoint Cumulative Updates Packages.
	In a multiserver environment you have to stop and start some services for a clean install of the updates.
	This script will do this for you automatically. 
	Just start the SharePoint Management Shell and run the script with the given parameter.
	
	The prerequisites to run this script:
	   - You are logged in to the server you want to patch with a farm admin account.
	   - You are a local administrator of the server.
	   - You started the SharePoint Management Shell with run as administrator.
	   - You have the buildnumber of the CU you want to install. You usually can retrieve the CU Buildversion from the KB article.
		
	There a to ways to install the CUs
	   - Local
	   - Remote
	
	Local way:
	-----------------
	Just place the extracted CU-Package ubersrvsp2013-kbXXXXXXXX-fullfile-x64-glb.exe into the same folder and start the script. Be sure
	to have only one .exe file in the folder.
	
	Remote way:
	-----------------
	The CU is on a network path which is accesible from the current server. Use the path parameter to point to the location of the cu.
		
.PARAMETER IsRestart
    This parameter is used internally by the script. If this parameter is set to true the SharePoint Configuration Wizard starts.
	You can call the script with this parameter when you started powershell as administrator.
.PARAMETER RunWizard
	Starts the script in an elevated powershell windows. Used by the AutoRun key.
.EXAMPLE
    C:\PS> ./AutoSPCUInstaller.ps1
    Installs the Cumulative Update with the parameter in the config file. The .exe file is on the same folder as the scripts.
.EXAMPLE	
	C:\PS> ./AutoSPCUInstaller.ps1 -IsRestart:$true
	Use this to start the SharePoint Configuration Wizard. Normally the wizard should start after reboot. 
	In case of error you can run this command on an elevated (Run as administrator) powershell command.
.NOTES
    Author: Ihsan Baris Bikmaz
    Date:   October 15, 2013  
.LINK
	http://blogs.msdn.com/b/russmax/archive/2013/04/01/why-sharepoint-2013-cumulative-update-takes-5-hours-to-install.aspx
#>

param(	
	[boolean] $IsRestart = $false,	
	[boolean] $RunWizard = $false	
)
  
# ------------------------------------
# Intro
# ------------------------------------
Clear-Host

Write-Host 
Write-Host
Write-Host -BackgroundColor White -ForegroundColor Blue "-------------------------------------------------------"   
Write-Host -BackgroundColor White -ForegroundColor Blue "Update Script for SharePoint Cumulative Updates        "   
Write-Host -BackgroundColor White -ForegroundColor Blue "                                                       "   
Write-Host -BackgroundColor White -ForegroundColor Blue "   1 .Place this script and the extracted CU in to     "   
Write-Host -BackgroundColor White -ForegroundColor Blue "      the same folder and start this script or use     "   
Write-Host -BackgroundColor White -ForegroundColor Blue "      the same folder and start this script or use     "   
Write-Host -BackgroundColor White -ForegroundColor Blue "      UpdateFilePath element in the xml config.        "   
Write-Host -BackgroundColor White -ForegroundColor Blue "                                                       "   
Write-Host -BackgroundColor White -ForegroundColor Blue "   2. Ensure that you logged in with Farm Account or   "   
Write-Host -BackgroundColor White -ForegroundColor Blue "      an account that has farm admin rights.           "   
Write-Host -BackgroundColor White -ForegroundColor Blue "                                                       "   
Write-Host -BackgroundColor White -ForegroundColor Blue "-------------------------------------------------------"
Write-Host
Write-Host

# ------------------------------------
# Load Functions
# ------------------------------------
$invocation = $myInvocation.MyCommand.Definition
$scriptDir  = [System.IO.Path]::GetDirectoryName($invocation)
$extLibPS1  = Join-Path $scriptDir "AutoSPCUInstaller_Func.ps1"
. $extLibPS1

# ------------------------------------
# Read XML Configuration
# ------------------------------------  
$configXML = Join-Path $scriptDir "AutoSPCUInstaller_Conf.xml"
[xml] $xml = Get-Content $configXML

$buildVersion = $xml.Configuration.BuildVersion
$updateFilePath = $xml.Configuration.UpdateFilePath

$spInternalVersion = Check-SPVersion

# ------------------------------------
# Global variables
# ------------------------------------  
  
$global:regRunKey  	= "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
$global:restartKey 	= "Restart-And-Resume"
$global:doRestart   = $true
$psConfigPath 		= "$env:CommonProgramFiles\Microsoft Shared\Web Server Extensions\$spInternalVersion\BIN\"
$svcSPTimerName 	= "SPTimerV4"
$svcSPSearchName 	= "OSearch$spInternalVersion"
$svcIISAdminName 	= "IISADMIN"
$svcSearchHostName 	= "SPSearchHostController"
$global:powershell = (Join-Path $env:windir "system32\WindowsPowerShell\v1.0\powershell.exe")	


# ------------------------------------
# Start Configuration Wizard
# ------------------------------------
Run-AsAdministrator $RunWizard
Start-ConfigurationWizard $IsRestart $psConfigPath $StartConfigUI


# ------------------------------------
# Checks
# ------------------------------------
Check-BuildVersion $buildVersion
Check-FarmAdminAccount
Check-IsAdminMode


# ------------------------------------
# Start Applying Patch
# ------------------------------------ 

$cuPackage  = Ensure-PackageExists $updateFilePath
Write-Host -ForegroundColor Magenta ">> Press Y/y to start installation, N/n to abort"  
$doContinue = Read-Host
Abort-Installation $doContinue

# Stop Search
Stop-WindowsService $svcSPSearchName
if ($spInternalVersion -gt 14) { Stop-WindowsService $svcSearchHostName }
# Stop IIS Admin
Stop-WindowsService $svcIISAdminName
# Stop SP Timer
Stop-WindowsService $svcSPTimerName
# Stop W3WP
Write-Host -ForegroundColor yellow ">> Stopping IIS W3WP Processes ..." 
iisreset -stop -noforce 

# Start Patch
Start-Patching $cuPackage

# Start SP Timer
Start-WindowsService $svcSPTimerName
# Start IIS Admin
Start-WindowsService $svcIISAdminName
# Start Search
if ($spInternalVersion -gt 14) { Start-WindowsService $svcSearchHostName }
Start-WindowsService $svcSPSearchName
# Start W3WP
Write-Host -ForegroundColor yellow ">> Starting IIS W3WP Processes ..." 
iisreset -start -noforce 

# Create Reboot
if ( $global:doRestart -eq $true )
{
	Create-AutorunKey
	Write-Host
	Write-Host -ForegroundColor green  ">> CU Installation complete.`n`n" 
	Write-Host -ForegroundColor yellow ">> After Restart the SharePoint Configuration Wizard will be started."
	$restart = Read-Host ">> PRESS ANY KEY TO RESTART."  
	Restart-Computer
}
else
{
	Write-Host -ForegroundColor green  ">> All services are restored. Fix the error and restart the script.`n`n" 
}


